<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
        <%@include file="/sunzbase.jsp"%>
<%@ page import="com.tyao.note.model.BFolder" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>文件夹管理</title>
<style type="text/css">
div#rMenu {position:absolute; visibility:hidden; top:0; background-color: #555;text-align: left;padding: 2px;}
div#rMenu ul li{
	margin: 1px 0;
	padding: 0 5px;
	cursor: pointer;
	list-style: none outside none;
	background-color: #FFF;
}
</style>

<link rel="stylesheet" href="resources/lib/zTree/v3/css/zTreeStyle/zTreeStyle.css" type="text/css">
</head>
<body class="pos-r">
<div id="fileDiv" style="display:none">
	<form id="fileForm" action="note/fileUpload" method="post" enctype="multipart/form-data">
    <div id="fade" class="black_overlay" style="visibility: visible;">
    	
	    <div id="light" class="white_content" style="width: 330px;padding: 20px 20px;">
		     <div style="padding: 0px 20px;">
		     	 <div style="float: left;padding-left: 40%;">上传文件</div><div style="float: right;font-size:15px;"><a href = "javascript:void(0)" onclick = "document.getElementById('light').style.display='none';document.getElementById('fade').style.display='none'">x</a></div>
		     </div>	
		     <br/>
		     <input type="file" id="fileUpload" value="" multiple name="fileUpload" onchange="getFileValue()" style="display:none" />
			 <div style="margin: 20px 10px;"> <ul id="fileLable"></ul> </div>
			 <div style="float: right;"><button type="button" id="startUp" class="btn btn-primary radius">开始上传</button> &nbsp;&nbsp;<button type="button" class="btn radius" onclick="document.getElementById('light').style.display='none';document.getElementById('fade').style.display='none'">取消</button></div>	     
	  		 <input id="folderId1" name="folderId1" type="hidden"/>
	    </div> 
	 </div>
    </form>
</div>
<div class="pos-a" style="width:200px;left:0;top:0; bottom:0; height:100%; border-right:1px solid #e5e5e5; background-color:#f5f5f5; overflow:auto;">
	<ul id="treeDemo" class="ztree"></ul>
</div>
<div style="margin-left:200px;">
	<nav class="breadcrumb"><i class="Hui-iconfont">&#xe67f;</i> 首页 <span class="c-gray en">&gt;</span> 文件管理 <span class="c-gray en">&gt;</span> 文件列表 <a class="btn btn-success radius r" style="line-height:1.6em;margin-top:3px" href="javascript:location.replace(location.href);" title="刷新" ><i class="Hui-iconfont">&#xe68f;</i></a></nav>
	<div class="page-container">
	<form action="" id="searchForm">
		<div class="text-c"> 日期范围：
			<input type="text" onfocus="WdatePicker({ maxDate:'#F{$dp.$D(\'logmax\')||\'%y-%M-%d\'}' })" id="logmin" name="logmin" class="input-text Wdate" style="width:120px;">
			-
			<input type="text" onfocus="WdatePicker({ minDate:'#F{$dp.$D(\'logmin\')}',maxDate:'%y-%M-%d' })" id="logmax" name="logmax" class="input-text Wdate" style="width:120px;">
			<input type="text" name="fileName" id="fileName" placeholder=" 文件名称" style="width:250px" class="input-text">
			<button name="fileSearch" id="fileSearch" class="btn btn-success" type="button"><i class="Hui-iconfont">&#xe665;</i> 搜文件</button>
			<input id="folderId" name="folderId" type="hidden"/>
		</div>
	</form>
		<div class="cl pd-5 bg-1 bk-gray mt-20"> <span class="l"><a href="javascript:;" onclick="datadel()" class="btn btn-danger radius"><i class="Hui-iconfont">&#xe6e2;</i> 批量删除</a> <a class="btn btn-primary radius" onclick="file_up()" href="javascript:;"><i class="Hui-iconfont">&#xe600;</i> 上传文件</a></span> </div>
		<div class="mt-20">
			<table class="table table-border table-bordered table-bg table-hover table-sort" width="100%">
				<thead>
					<tr class="text-c">
						<th width="40"><input name="" id="allChk" type="checkbox" value=""></th>
						<th>名称</th>
						<th>类型</th>
						<th>大小</th>
						<th>上传日期</th>
						<th>操作</th>
					</tr>
				</thead>
				<tbody>
	<!-- 				<tr class="text-c va-m">
						<td><input name="" type="checkbox" value=""></td>
						<td><a onClick="product_show('文件内容','#','10001')" href="javascript:;">新建文本文档</a></td>
						<td class="text-l text-c">2018-08-08 08:08:08</td>
						<td class="text-l text-c">文本文档</td>
						<td><span class="price">356</span> KB</td>
						<td class="td-manage"><a style="text-decoration:none" onClick="product_stop(this,'10001')" href="javascript:;" title="下载"><i class="Hui-iconfont">&#xe6de;</i></a> <a style="text-decoration:none" class="ml-5" onClick="product_edit('产品编辑','product-add.html','10001')" href="javascript:;" title="编辑"><i class="Hui-iconfont">&#xe6df;</i></a> <a style="text-decoration:none" class="ml-5" onClick="product_del(this,'10001')" href="javascript:;" title="删除"><i class="Hui-iconfont">&#xe6e2;</i></a></td>
					</tr> -->
				</tbody>
			</table>
		</div>
	</div>
</div>
<div id="rMenu">
	<ul>
		<li id="m_add" onclick="addTreeNode();">新建文件夹</li>
		<li id="m_del" onclick="removeTreeNode();">删除文件夹</li>
		<li id="m_rename">重命名</li>
		<li id="copy" onclick="return false;">复制</li>
		<li id="cut" onclick="return false;">剪切</li>
		<li id="paste" onclick="return false;">粘贴</li>
	</ul>
</div>

<!--请在下方写此页面业务相关的脚本-->
<script type="text/javascript" src="resources/lib/zTree/v3/js/jquery.ztree.all-3.5.min.js"></script>
<script type="text/javascript" src="${webRoot}/resources/lib/My97DatePicker/4.8/WdatePicker.js"></script> 
<script type="text/javascript" src="resources/lib/datatables/1.10.0/jquery.dataTables.min.js"></script> 
<script type="text/javascript" src="resources/lib/laypage/1.2/laypage.js"></script>
<script type="text/javascript">
//获取搜索中各选项的值
function getParameters(){
	var params = $("#searchForm").serializeArray();
	//console.log(params);
	var values = {};
	for (var item in params) {
	   values[params[item].name] = params[item].value;
	}
	//console.log(values);
	return values;
}
/* 搜索 */
$("#fileSearch").on("click",function(){
	var datatable = $('.table-sort').DataTable();
	//console.log(datatable);
	//datatable.ajax.url( '${webRoot}/note/searchUser' ).load();
	datatable.settings()[0].ajax.data = getParameters();
	datatable.ajax.reload();
});
$('.table-sort').dataTable({
	"aaSorting": [[ 2, "desc" ]],//默认第几个排序
	"bStateSave": true,//状态保存
	"aoColumnDefs": [
	  {"orderable":false,"aTargets":[0,5]}// 制定列不参与排序
	],
	 ajax:{  
	       url:"note/fileList",  
	       type:'post',  
	       data:getParameters()
	   },
	 columns:[
	  { "data": null,"render":function(data,type,full,meta){
		  return '<input type="checkbox" onclick="check()" name="items" value="'+data.id+'">';
		  } },   
 	  { "data": "accName" },  
 	  { "data": "accExt" },
 	  { "data": null,"render":function(data,type,full,meta){
 		  return getFileSize(data.accSize);
 		  }
 	  },
 	  { "data": null,"render":function (data,type,full,meta){
 		  return formatDate(data.createTime,true);
 	  		}
 	  }, 
 	  {"data":null ,"render": function ( data, type, full, meta ) {
 	      return '<a title="下载" href="note/fileDown?id='+data.id+'" onclick="" style="text-decoration:none"><i class="Hui-iconfont">&#xe6de;</i></a><a title="移动到" href="javascript:;" onclick="file_move(\'文件移动\',\'note/fileMove?id='+data.id+'\',\'400\',\'440\')" class="ml-5" style="text-decoration:none"><i class="Hui-iconfont">&#xe6f7;</i></a><a title="删除" href="javascript:;" onclick="product_del(this,'+data.id+')" class="ml-5" style="text-decoration:none"><i class="Hui-iconfont">&#xe6e2;</i></a>';
 	      }
 	  }
 ]
});
/*文件-上传*/
	$(document).ready(function(){
		 $("#startUp").click(function(){
			 debugger;
			 $("#fileForm").ajaxSubmit(function(result){
				if(result.success){
					$("#fileDiv").css("display","none");
					$('#light').css("display",'none');
					$('#fade').css("display","none");
					layer.msg(result.msg,{icon:6});
					$("#fileSearch").click();
				}
			});
		 })
	});
	function file_up(){
		var folderId=$("#folderId").val();
		if(folderId==${defaultFolder.id}){
			alert("文件无法上传到根目录，请选择其他文件夹！");
		}else
			 $("#fileUpload").click();
	}
	function getFileValue(){
		 debugger;
		 $("#fileLable").empty();
		    var fp = $("#fileUpload");
		    var lg = fp[0].files.length; // get length
		    var items = fp[0].files;
		    var fragment = "";
		     
		    if (lg > 0) {
		        for (var i = 0; i < lg; i++) {
		            var fileName = items[i].name; // get file name
		            var fileSize = items[i].size; // get file size 
		            var fileType = items[i].type; // get file type
		 
		            // append li to UL tag to display File info
		            fragment += "<li><i class='Hui-iconfont'>&#xe600;</i>&nbsp;&nbsp" + fileName + " (<b>" + fileSize + "</b> bytes) </li>";
		        }
		 
		        $("#fileLable").append(fragment);
		    }
			// $("#fileDiv").style.display='block';
			$("#fileDiv").css("display","block");
			$("#light").css("display","block");
			$("#fade").css("display","block");
	}
	/*文件-批量删除*/
	$("#allChk").click(function(){
		if(this.checked){
			$("input[name='items']:checkbox").each(function(){
				$(this).attr("checked",true);
			})
		}else{
			$("input[name='items']:checkbox").each(function(){
				$(this).attr("checked",false);
			})
		}
	});
	function check(){	
			if($(":checkbox[name='items']").length==$(":checkbox[name='items']:checked").length){
				$("#allChk").prop("checked",true);
			} else{
				 $("#allChk").prop("checked",false);
			}
		};
	 function datadel(){
		 var ids=[];
		 if($("input[name='items']:checked").length>0){
			 $("input[name='items']:checked").each(function(){ 
		         ids.push($(this).attr("value"));  
			 })
		 }else{
			 layer.alert("请先选择删除项！");
			 return false;
		 }
			var delIds=ids.join(","); 
			console.log(delIds);
			$.ajax({
				type: 'POST',
				url: 'note/filesDel',
				data:{accIds:delIds},
				dataType: 'json',
				success: function(data){
					if(data.success){
						$('#fileSearch').click();
						layer.msg('已删除!',{icon:1,time:1000});					
						$(obj).parents("tr").remove();					
					}else{
						layer.msg('删除失败!',{icon:1,time:1000});
					}
				},
				error:function(data) {
					console.log(data.msg);
				}
			});
	 }

/*文件-删除*/
function product_del(obj,id){
	layer.confirm('确认要删除吗？',function(index){
		$.ajax({
			type: 'POST',
			url: 'note/filesDel',
			data:{accIds:id},
			dataType: 'json',
			success: function(data){
				$("#fileSearch").click();
				$(obj).parents("tr").remove();
				layer.msg('已删除!',{icon:1,time:1000});
			},
			error:function(data) {
				console.log(data.msg);
			},
		});	
	});
}
/*文件-移动*/
function file_move(title,url,w,h){
	layer_show(title,url,w,h);
}
function getFileSize(fileByte) {
	var fileSizeByte = fileByte; 
	var fileSizeMsg = ""; 
	if (fileSizeByte < 1048576) 
		fileSizeMsg = (fileSizeByte / 1024).toFixed(2) + "KB"; 
	else if (fileSizeByte == 1048576)
		fileSizeMsg = "1MB";
	else if (fileSizeByte > 1048576 && fileSizeByte < 1073741824) 
		fileSizeMsg = (fileSizeByte / (1024 * 1024)).toFixed(2) + "MB"; 
	else if (fileSizeByte > 1048576 && fileSizeByte == 1073741824) 
		fileSizeMsg = "1GB"; 
	else if (fileSizeByte > 1073741824 && fileSizeByte < 1099511627776) 
		fileSizeMsg = (fileSizeByte / (1024 * 1024 * 1024)).toFixed(2) + "GB"; 
	else fileSizeMsg = "文件超过1TB"; 
	return fileSizeMsg; 
	}
</script>
<SCRIPT type="text/javascript">
/* 左侧栏 */
var zNodes = [];
var zTree, rMenu,newname;
$(function(){
	$.ajax({
		url:"note/createRootFolder",
		data:{},
		dataType:"json",
		type:"POST",
		async:false,
		success:function(result){
			var znodes = {};
			for (var i = 0;i<result.data.length;i++) {
				var folderParentId;
				if(result.data[i].folderName == '${user.username}'){
					folderParentId = result.data[i].id;
				}
				if(result.data[i].folderDefaut == 1){
					znodes = {"id":result.data[i].id,"pid":result.data[i].folderParentId,"name":result.data[i].folderName,"open":true,"noR":true,topNode:true};
				}else if(result.data[i].folderParentId == folderParentId){
					znodes = {"id":result.data[i].id,"pid":result.data[i].folderParentId,"name":result.data[i].folderName,"open":true,"isParent":true};
				}else if(result.data[i].folderName == '${user.username}'){
					znodes = {"id":result.data[i].id,"pid":result.data[i].folderParentId,"name":result.data[i].folderName,"open":true,"isParent":true};
				}else{
					znodes = {"id":result.data[i].id,"pid":result.data[i].folderParentId,"name":result.data[i].folderName};
				}
				zNodes.push(znodes);
			}
			$.fn.zTree.init($("#treeDemo"), setting, zNodes);
			zTree = $.fn.zTree.getZTreeObj("treeDemo");
			rMenu = $("#rMenu");
			//重命名部门
		    $("#m_rename").on("click",function(){
		        renameTreeNode();
		    });
		    $("#copy").bind("click", copy);
			$("#cut").bind("click", cut);
			$("#paste").bind("click", paste);
		}
	});
});
var setting = {
	view: {
		showLine: false
	},
	data: {
		simpleData: {
			enable:true,
			idKey: "id",
			pIdKey: "pid",
			rootPId: ""
		}
	},
	edit: {
		enable: true,
		editNameSelectAll: true,
		showRenameBtn: false,
		showRemoveBtn: false
	},
	callback: {
		onRightClick: OnRightClick,
		onClick: zTreeOnClick,
		beforeRename: beforeRename,
		beforeDrag: beforeDrag
	}
};
		
function renameTreeNode(event) {
	hideRMenu();
	var nodes = zTree.getSelectedNodes(),
	treeNode = nodes[0];
	if (nodes.length == 0) {
		layer.alert("请先选择一个部门");
		return;
	}
	zTree.editName(treeNode);
	//监听enter事件
	$("#"+treeNode.tId).on("keydown",function(event){
		if(event.keyCode==13){
			renameFolderName(treeNode);
		}
	});
	//监听单击事件
	$(".pos-r").on("mousedown",function(event){
		if(event.button==0){
			renameFolderName(treeNode);
		}else{
			return;
		}
	});
};
//发送重命名请求到服务器
function renameFolderName(treeNode){
	console.log(treeNode.name);
	var id = treeNode.id;
	$.ajax({
		url:"${webRoot}/note/renameFolderInfo",
		data:{"folderName":treeNode.name,"id":id},
		type:"post",
		dataType:"json",
		success:function(result){
			if(!result.success){
				layer.msg(result.msg,{icon:2});
			}
		}
	});
}
		
function beforeRename(treeId, treeNode, newName, isCancel) {
	if (newName.length == 0) {
		layer.alert("节点名称不能为空.");
		return false;
	}
	return true;
}
		
/* 单击事件 */
function zTreeOnClick(event, treeId, treeNode) {
	var id = zTree.getSelectedNodes()[0].id;
	$("#folderId").val(id);
	$("#folderId1").val(id);
	$("#fileSearch").click();
}
		
function OnRightClick(event, treeId, treeNode) {
	if (treeNode.name == '${user.username}') {
		zTree.selectNode(treeNode);
		showRMenu("root", event.clientX, event.clientY);
	} else if (treeNode && !treeNode.noR) {
		zTree.selectNode(treeNode);
		showRMenu("node", event.clientX, event.clientY);
	}
}

function showRMenu(type, x, y) {
	$("#rMenu ul").show();
	if (type=="root") {
		$("#m_add").show();
		$("#m_del").hide();
		$("#m_rename").hide();
		$("#copy").hide();
		$("#cut").hide();
		$("#paste").hide();
	} else {
		$("#m_add").show();
		$("#m_del").show();
		$("#m_rename").show();
		$("#copy").show();
		$("#cut").show();
		$("#paste").show();
	}
	y += document.body.scrollTop;
    x += document.body.scrollLeft;
    rMenu.css({"top":y+"px", "left":x+"px", "visibility":"visible"});
	$("body").bind("mousedown", onBodyMouseDown);
}

function hideRMenu() {
	if (rMenu) rMenu.css({"visibility": "hidden"});
	$("body").unbind("mousedown", onBodyMouseDown);
}

function onBodyMouseDown(event){
	if (!(event.target.id == "rMenu" || $(event.target).parents("#rMenu").length>0)) {
		rMenu.css({"visibility" : "hidden"});
	}
}
var addCount = 1;
function addTreeNode() {
	hideRMenu();
	var newNode = { name:"新建文件夹" + (addCount++)};
	var id = zTree.getSelectedNodes()[0].id;
	if (zTree.getSelectedNodes()[0]) {
		$.ajax({
			url:"${webRoot}/note/createFolder",
			data:{"folderName":newNode.name,"id":id},
			type:"post",
			dataType:"json",
			success:function(result){
				if(result.success){
					znodes = {"id":result.data.id,"pid":result.data.folderParentId,"name":newNode.name,isParent:true};
					zNodes.push(znodes);
					newNode.checked = zTree.getSelectedNodes()[0].checked;
					zTree.addNodes(zTree.getSelectedNodes()[0], newNode);
					$.fn.zTree.init($("#treeDemo"), setting, zNodes);
				}else{
					layer.msg(result.msg,{icon:2});
				}
			}
		});
	} else {
		zTree.addNodes(null, newNode);
	}
}
function removeTreeNode() {
	hideRMenu();
	var nodes = zTree.getSelectedNodes();
	if (nodes && nodes.length>0) {
		var deleteBatch;
		var id = zTree.getSelectedNodes()[0].id;
		var msg = "可能包含子文件夹，将连同子文件夹一起删掉。\n\n请确认！";
		layer.confirm(msg,function(){
			if (nodes[0].children && nodes[0].children.length > 0) {
				deleteBatch = true;
			} else {
				deleteBatch = false;
			}
			zTree.removeNode(nodes[0]);
			$.ajax({
				url:"${webRoot}/note/removeFolders",
				data:{"id":id,"deleteBatch":deleteBatch},
				type:"post",
				dataType:"json",
				success:function(result){
					if(result.success){
						layer.msg(result.msg,{icon:1});
					}
				}
			});
		});
	}
}

function beforeDrag(treeId, treeNodes) {
	return false;
}

function fontCss(treeNode) {
	var aObj = $("#" + treeNode.tId + "_a");
	aObj.removeClass("copy").removeClass("cut");
	if (treeNode === curSrcNode) {
		if (curType == "copy") {
			aObj.addClass(curType);
		} else {
			aObj.addClass(curType);
		}			
	}
}

var curSrcNode, curType;
function setCurSrcNode(treeNode) {
	var zTree = $.fn.zTree.getZTreeObj("treeDemo");
	if (curSrcNode) {
		delete curSrcNode.isCur;
		var tmpNode = curSrcNode;
		curSrcNode = null;
		fontCss(tmpNode);
	}
	curSrcNode = treeNode;
	if (!treeNode) return;

	curSrcNode.isCur = true;			
	zTree.cancelSelectedNode();
	fontCss(curSrcNode);
}

var id,folderParentId;
function copy(e) {
	hideRMenu();
	var zTree = $.fn.zTree.getZTreeObj("treeDemo"),
	nodes = zTree.getSelectedNodes();
	if (nodes.length == 0) {
		layer.alert("请先选择需要操作的文件夹");
		return;
	}
	curType = "copy";
	setCurSrcNode(nodes[0]);
	id = nodes[0].id;
}

function cut(e) {
	hideRMenu();
	var zTree = $.fn.zTree.getZTreeObj("treeDemo"),
	nodes = zTree.getSelectedNodes();
	if (nodes.length == 0) {
		layer.alert("请先选择需要操作的文件夹");
		return;
	}
	curType = "cut";
	setCurSrcNode(nodes[0]);
	id = nodes[0].id;
}

function paste(e) {
	hideRMenu();
	if (!curSrcNode) {
		layer.alert("请先选择需要操作的文件夹 复制 / 剪切");
		return;
	}
	var zTree = $.fn.zTree.getZTreeObj("treeDemo"),
	nodes = zTree.getSelectedNodes(),
	targetNode = nodes.length>0? nodes[0]:null;
	folderParentId = nodes[0].id;
	if (curSrcNode === targetNode) {
		layer.alert("不能移动，源文件夹 与 目标文件夹相同");
		return;
	} else if (curType === "cut" && ((!!targetNode && curSrcNode.parentTId === targetNode.tId) || (!targetNode && !curSrcNode.parentTId))) {
		layer.alert("不能移动，源文件夹 已经存在于 目标文件夹中");
		return;
	} else if (curType === "copy") {
		$.ajax({
			url:"${webRoot}/note/copyFolder",
			data:{
				"id":id,"folderParentId":folderParentId,"isCut":false
			},
			type:"post",
			dataType:"json",
			success:function(result){
				if(!result.success){
					layer.alert(result.msg);
				}
			}
		});
		targetNode = zTree.copyNode(targetNode, curSrcNode, "inner");
	} else if (curType === "cut") {
		$.ajax({
			url:"${webRoot}/note/cutFolder",
			data:{
				"id":id,"folderParentId":folderParentId,"isCut":true
			},
			type:"post",
			dataType:"json",
			success:function(result){
				if(!result.success){
					layer.alert(result.msg);
				}
			}
		});
		targetNode = zTree.moveNode(targetNode, curSrcNode, "inner");
		if (!targetNode) {
			layer.alert("剪切失败，源文件夹是目标文件夹的上级文件");
		}
		targetNode = curSrcNode;
	}
	setCurSrcNode();
	delete targetNode.isCur;
	zTree.selectNode(targetNode);
}

</SCRIPT>
</body>
</html>